package background;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;

public class DisappearRequest1 implements Runnable{

    static  DisappearRequest1 instance = new DisappearRequest1();
    static  int i = 0;
    final boolean[] marked = new boolean[100000];
    static volatile CyclicBarrier cyclicBarrier1 = new CyclicBarrier(2);
    static volatile CyclicBarrier cyclicBarrier2 = new CyclicBarrier(2);


    //原子类
    static AtomicInteger realIndex = new AtomicInteger();
    static AtomicInteger wrongCount = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(instance);
        Thread thread2 = new Thread(instance);

        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();

        System.out.println("表面上的结果"+i);
        System.out.println("真正运行的次数"+realIndex.get());
        System.out.println("错误次数"+wrongCount.get());
    }

    @Override
    public void run() {
        marked[0] = true;
        for (int j = 0 ;j<10000;j++){

            try {
                cyclicBarrier2.reset();
                cyclicBarrier1.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }

            i++;

            try {
                cyclicBarrier1.reset();
                cyclicBarrier2.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }

            realIndex.incrementAndGet();
            synchronized (instance) {
                if (marked[i]  && marked[i-1]){
                    System.out.println("发生错误"+i);
                    wrongCount.incrementAndGet();

                }
                marked[i] = true;
            }

        }
    }
}
